namespace TomatoBreak.Web
{
    using System;
    using System.Web.Mvc;

    using NHibernate;

    public class Transaction : IMvcFilter, IActionFilter
    {
        private readonly ISession session;

        public Transaction(ISession session)
        {
            if (session == null)
            {
                throw new ArgumentNullException("session");
            }

            this.session = session;
            Order = 1;
        }

        public int Order { get; set; }

        public bool AllowMultiple
        {
            get { return false; }
        }

        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (session.Transaction == null || !session.Transaction.IsActive)
            {
                session.BeginTransaction();
            }
        }

        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            if ((session.Transaction == null) || !session.Transaction.IsActive)
            {
                return;
            }

            if (filterContext.Exception != null && !filterContext.ExceptionHandled)
            {
                session.Transaction.Rollback();
            }
            else
            {
                session.Transaction.Commit();
            }
        }
    }
}